const { TAG_IS_EXIST, SERVER_ERR, TEXT_IS_REQUIRED } = require("../config/error");
const tagService = require("../service/tag.service");

const verifyTag = async (ctx, next) => {
  try {
    const { user ={}} = ctx;
      const { id: userId = 1 } = user;
    const { text } = ctx.request.body;
    if (!text) {
      ctx.app.emit("error", TEXT_IS_REQUIRED, ctx);
      return;
    }
    const arr = await tagService.findName({ text, userId });
    if (arr.length) {
      ctx.app.emit("error", TAG_IS_EXIST, ctx);
      return;
    }
    await next();
  } catch (error) {
    ctx.error = error;
    ctx.app.emit("error", SERVER_ERR, ctx);
  }
};
module.exports = verifyTag;
